package mudus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.util.Stack;

public class LogFile {    
    
    //bikin log file dari struktur direktori target, nama log file
    //adalah nama dari direktori target dan disimpan di parent targetDir
    public static File createLogFile(UserInfo userInfo) throws FileNotFoundException {
        String targetDirPath = userInfo.getRepoPath();
        File targetDir = new File(targetDirPath);     
        URI base = targetDir.toURI();
        File logFile = new File(GlobalSettings.LOGFILE_PATH, userInfo.getUsername() + ".log");   
        FileOutputStream fos = new FileOutputStream(logFile);                        
        PrintStream out = new PrintStream(fos);                    
        
        Stack<File> files = new Stack<File>();                                
        for(File child : targetDir.listFiles()) {
            files.add(child);
        }
        
        while(!files.empty()) {
            File file = files.pop();
            String relativePath = base.relativize(file.getParentFile().toURI()).getPath();
            out.println(relativePath + "|" + file.getName() + "|" + file.isFile() + "|" + file.lastModified());                                    
            //System.out.println(relativePath + "|" + file.getName() + "|" + file.isFile() + "|" + file.lastModified());
            if(file.isDirectory()) {
                String[] childs = file.list();               
                for(File child : file.listFiles()) {
                    files.add(child);
                }
            }
        }       
        
        return logFile;                
    }         
    
    public static File getLogFile(UserInfo userInfo) throws FileNotFoundException {
        File file = new File(userInfo.getLogPath());
        if(file.exists()) {
            return file;
        }
        return createLogFile(userInfo);
    }
    
    public static void main(String[] args) throws FileNotFoundException {   
        UserInfo userInfo = new UserInfo(1, "hilmanbeyri");
        LogFile.createLogFile(userInfo);
    }
}
